<template>
	<view>
		<div ref="pdfContainer" class="pdf-container"></div>
	</view>
</template>

<script>
	import * as pdfjsLib from 'pdfjs-dist';
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			this.loadPdf()
		},
		methods: {
			async loadPdf() {
				// #ifndef VUE3
				const url = {
					url: './static/034001700111-45763370.pdf',
					cMapUrl: "./cmaps/",
					standardFontDataUrl: "./standard_fonts/",
					cMapPacked: true
				};
				// VUE2 不能使用import.meta.url
				pdfjsLib.GlobalWorkerOptions.workerSrc = './static/pdf.worker.min.js';
				// #endif
				// #ifdef VUE3
				const url = {
					url: './static/034001700111-45763370.pdf',
					cMapUrl: "../cmaps/",
					standardFontDataUrl: "../standard_fonts/",
					cMapPacked: true
				};
				pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
					'pdfjs-dist/build/pdf.worker.min.js',
					import.meta.url
				).toString();
				// #endif
				const loadingTask = pdfjsLib.getDocument(url);
				loadingTask.promise.then(pdf => {
					for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
						this.renderPdf(pdf, pageNum); // 渲染第一页
					}
				}).catch(error => {
					console.error('Error loading PDF:', error);
				});
			},
			renderPdf(pdf, pageNum) {
				pdf.getPage(pageNum).then(page => {
					const scale = window.devicePixelRatio;
					const viewport = page.getViewport({ scale}); // 设置缩放比例
					const canvas = document.createElement('canvas');
					const ctx = uni.createCanvasContext('myCanvas', this);
					const context = canvas.getContext('2d')
					canvas.height = viewport.height;
					canvas.width = viewport.width;
					canvas.style.width = "100%";

					this.$refs.pdfContainer.appendChild(canvas); // 将canvas添加到DOM中
					const renderContext = {
						canvasContext: context,
						viewport: viewport,
					};
					const renderTask = page.render(renderContext);
					renderTask.promise.then(() => {
						console.log('Page rendered');
					});
				});
			}
		}
	}
</script>

<style>
	.pdf-container {
		width: 100vw;
		height: 100vh;
		overflow: scroll;
	}
	canvas {
		width: 100%;
	}
</style>
